package keter.framework.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import keter.framework.web.security.CaptchaCache;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("captcha")
public class CaptchaController extends AbstractBaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    private static final long serialVersionUID = 1L;
    private static final String ATTRIBUTE_CAPTCHA = "captcha";
    
    /**
     * <p>
     * Method ：refreshImage
     * <p>
     * Description : 获取新验证码：调用即刷新
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     * @author 顾力行-gulixing@msn.com
     */
    @RequestMapping(value = "/new", method = RequestMethod.GET)
    protected void newImage(final HttpServletRequest request, final HttpServletResponse response)
            throws ServletException {
        final CaptchaCache cache = createAndAddKaptcha(request.getSession());
//        logger.info("生成验证码:{}",cache.actualText);
        generate(response, cache);
    }
    
    private void generate(final HttpServletResponse response, final CaptchaCache cache) {
        OutputStreamWriter out = null;
        try {
            attachImageToResponse(cache.image, response);
//            logger.info("code is:{}", cache.actualText);
            out = new OutputStreamWriter(response.getOutputStream());
            out.flush();
        } catch (IOException e) {
            logger.error("验证码图像生成异常!");
        } 
    }

    /**
     * @param image
     * @param response
     * @throws IOException
     */
    private static void attachImageToResponse(final BufferedImage image, final HttpServletResponse response)
            throws IOException {
        // this may cause problems depending on the environment, best to disable
        // it
        if (ImageIO.getUseCache()) {
            ImageIO.setUseCache(false);
        }
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/png");
        ImageIO.write(image, "png", response.getOutputStream());
    }

    /**
     * @param session
     * @return
     */
    public String getCaptchaCode(final HttpSession session) {
        String attribute = (String)session.getAttribute(ATTRIBUTE_CAPTCHA);
        return StringUtils.isEmpty(attribute)?null:attribute;
    }
    
    /**
     * <p>Method ：dropCaptcha
     * <p>Description : 对通过校验的验证码进行废弃处理
     *
     * @param session 
     * @author  顾力行-gulixing@msn.com
     */
    public void dropCaptcha(final HttpSession session) {
        logger.info("废弃当前验证码...");
        session.setAttribute(ATTRIBUTE_CAPTCHA, null);
    }

    /**
     * @param session
     * @return
     */
    private CaptchaCache createAndAddKaptcha(final HttpSession session) {
        final CaptchaCache captchaCache = new CaptchaCache();
        session.setAttribute(ATTRIBUTE_CAPTCHA, captchaCache.actualText);
        return captchaCache;
    }
}
